package com.health.central_authentication.config;

import com.health.central_authentication.filter.DGUTCheckTokenFilter;
import com.health.central_authentication.handler.DGUTAccessDeniedHandler;
import com.health.central_authentication.handler.DGUTAuthenticationEntryPoint;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.annotation.Resource;

/**
 * 莞工中央认证安全配置
 * @author: zipeng Li
 * 2021/6/14  19:53
 */
@Configuration
@Order(99)
public class DGUTSecurityConfig extends WebSecurityConfigurerAdapter {
    @Resource
    private DGUTAccessDeniedHandler dgutAccessDeniedHandler;
    @Resource
    private DGUTAuthenticationEntryPoint dgutAuthenticationEntryPoint;
    @Resource
    private DGUTCheckTokenFilter dgutCheckTokenFilter;

    /**
     * 配置权限资源
     * @param http
     * @throws Exception
     */
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            // 只拦截检查'/api/user/**'的请求
            .antMatcher("/api/user/**").authorizeRequests().anyRequest().hasAuthority("USER")
            .and().csrf().disable()
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS)
            .and()
                .exceptionHandling()
                .authenticationEntryPoint(dgutAuthenticationEntryPoint)
                .accessDeniedHandler(dgutAccessDeniedHandler);
        http.addFilterBefore(dgutCheckTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }
}